package org.rc.controller;


import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.rc.cache.PersonnelNameCache;
import org.rc.dto.*;
import org.rc.entity.Personnel;
import org.rc.service.PersonnelService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/personal")
public class PersonnelController {

    @Value("${file.save.path}")
    private String fileSavePath;

    @Autowired
    private PersonnelService personnelService;

    @Autowired
    private PersonnelNameCache personnelNameCache;

    @PostMapping("/upload")
    public Res uploadFile(@RequestParam("file") MultipartFile file){
        if(null == file){
            return Res.failure("请选择上传到的文档！");
        }
        String fileName = file.getOriginalFilename();
        assert fileName != null;
        if(!fileName.contains(".xls") || !fileName.contains(".xlsx")){
            return Res.failure("请上传excel格式文件");
        }
        String fullFilePath = fileSavePath +File.separator+fileName;
        InputStream inputStream = null;
        try{
            inputStream = file.getInputStream();
            File saveFile = new File(fullFilePath);
            if(saveFile.exists()){
                saveFile.delete();
            }
            FileUtils.copyInputStreamToFile(inputStream,saveFile);
        }catch (Exception e){
            log.error("文件写入磁盘失败，e--->",e);
        }finally {
            if(null != inputStream){
                try{
                    inputStream.close();
                }catch (Exception e){
                    log.error("关闭流失败,e--->",e);
                }

            }
        }
        //全量导入，删除之前入库的数据
        personnelService.removeAllPersonnel();
        List<Personnel> personnels = new ArrayList<>();
        ExcelReader reader =null;
        try{
            reader = ExcelUtil.getReader(fullFilePath);
            List<Map<String, Object>> sheet = reader.readAll();
            if(CollectionUtils.isEmpty(sheet)){
                return Res.failure("文件内容为空");
            }
            SimpleDateFormat source = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            SimpleDateFormat target = new SimpleDateFormat("yyyy-MM-dd");
            for (Map<String, Object> row : sheet) {
                Personnel personnel = new Personnel();
                if(null!=row.get("姓名")){
                    personnel.setName(String.valueOf(row.get("姓名")).trim());
                }
                if(null!=row.get("性别")){
                    personnel.setGender(String.valueOf(row.get("性别")));
                }
                if(null!=row.get("出生年月")){
                    String birth = String.valueOf(row.get("出生年月"));
                    if(StringUtils.isNotEmpty(birth)){
                        try {
                            Date date = source.parse(birth);
                            birth = target.format(date);
                        }catch (Exception e){
                            log.error("日期转换错误，e--->",e);
                        }
                        personnel.setBirthday(birth);
                    }
                }
                if(null!=row.get("家庭住址")){
                    personnel.setAddress(String.valueOf(row.get("家庭住址")));
                }
                if(null!=row.get("工作单位")){
                    personnel.setWorkUnit(String.valueOf(row.get("工作单位")));
                }
                personnels.add(personnel);
            }
            personnelService.batchAddPersonnel(personnels);
        }catch (Exception e){
            log.error("读取excel失败，e--->",e);
            return Res.failure("读取excel失败");
        }finally {
            assert reader != null;
            reader.close();
        }
        personnelNameCache.reloadNames();
        return Res.success("数据导入成功");
    }

    @PostMapping("/byName")
    public Res getPersonByName(@RequestBody PersonQueryDto personQueryDto){
        String name = personQueryDto.getName();
        if(StringUtils.isEmpty(name)){
            return Res.failure("姓名不能为空");
        }
        List<String> similarNames = new ArrayList<>();
        similarNames.add(name);
        if(name.length()>2){
            similarNames.add(name.substring(0,2));
        }
        return Res.success(personnelService.getByNames(similarNames));
    }

    @PostMapping("/page")
    public Res getPersonPage(@RequestBody PersonPageDto personPageDto){
        return Res.success(PageDto.of(personnelService.getPersonPage(personPageDto)));
    }

}
